<template>
	<div id="add-edit-dep-manage" class="page-public-s">
		<el-dialog :title="titleCon" v-model="isUseDialog" draggable :close-on-click-modal="false" :close-on-press-escape="false" width="50%" :before-close="handleClose" :destroy-on-close="true" @close="clean">
			<!-- 一般作业人员 -->
			<el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="80px" :rules="rules">
				<el-divider content-position="left">基础信息</el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="人员姓名" prop="empName" :label-width="formLabelWidth">
							<el-input v-model="ruleForm.empName" placeholder="请输入姓名" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="岗位" prop="posIds" :label-width="formLabelWidth">
							<el-select @change="posChange" multiple v-model="ruleForm.posIds" placeholder="请选择岗位" clearable>
								<el-option v-for="item in posIdList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="员工工号" prop="jobNum" :label-width="formLabelWidth">
							<el-input v-model="ruleForm.jobNum" placeholder="请输入员工工号" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="部门名称" prop="orgName" :label-width="formLabelWidth">
							<el-tree-select
								ref="treeRef"
								v-model="ruleForm.orgName"
								:data="treeData"
								:default-expand-all="true"
								node-key="value"
								:props="treeProps"
								check-strictly
								:render-after-expand="false"
								@change="orgChange"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="人员性别" :label-width="formLabelWidth">
							<el-radio-group v-model="ruleForm.gender">
								<el-radio label="1">男</el-radio>
								<el-radio label="2">女</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="就职状态" :label-width="formLabelWidth">
							<el-radio-group v-model="ruleForm.isEnable">
								<el-radio :label="true">在职</el-radio>
								<el-radio :label="false">离职</el-radio>
							</el-radio-group>
                            <!-- <el-switch
                                v-model="ruleForm.isEnable"
                                active-color="#07AAF9"
                                inactive-color="#FF5F33"
                                inline-prompt
                                active-text="在职"
                                inactive-text="离职"
                            /> -->
                        </el-form-item>
                    </el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="婚姻状况" prop="maritalStatus" :label-width="formLabelWidth">
							<!-- <el-input type="text" v-model="ruleForm.maritalStatus" placeholder="请输入婚姻状况" clearable /> -->
							<el-select v-model="ruleForm.maritalStatus" placeholder="请选择婚姻状况" clearable>
								<el-option v-for="item in maritalStatusOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="政治身份" prop="politicalIdentity" :label-width="formLabelWidth">
							<!-- <el-input type="text" v-model="ruleForm.politicalIdentity" placeholder="请输入政治身份" clearable /> -->
							<el-select v-model="ruleForm.politicalIdentity" placeholder="请选择政治身份" clearable>
								<el-option v-for="item in politicalIdentityOptions" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="Email" :label-width="formLabelWidth">
							<el-input type="text" v-model="ruleForm.email" placeholder="请输入邮箱" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="联系方式" :label-width="formLabelWidth">
							<el-input pattern="[0-9]" oninput="if(value.length>11)value=value.slice(0,11)" type="text" v-model="ruleForm.phone" placeholder="请输入手机号" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="紧急联系人号码"  :label-width="formLabelWidth">
							<el-input pattern="[0-9]" oninput="if(value.length>11)value=value.slice(0,11)" type="text" v-model="ruleForm.emergencyPhone" placeholder="请输入手机号" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="身份证号" prop="cardId" :label-width="formLabelWidth">
							<el-input v-model="ruleForm.cardId" type="text" placeholder="请输入身份证号" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="家庭住址" prop="familyAddress" :label-width="formLabelWidth">
							<el-input v-model="ruleForm.familyAddress" type="text" placeholder="请输入家庭住址" clearable />
						</el-form-item>
					</el-col>
					<!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="体检提交数量" :label-width="formLabelWidth">
                            <el-input v-model="ruleForm.physicalCounts" disabled readonly type="text" placeholder="请输入体检提交数量" clearable />
                        </el-form-item>
                    </el-col> -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="入职日期" prop="inductionDate" :label-width="formLabelWidth">
							<el-date-picker v-model="ruleForm.inductionDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期"> </el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="离职日期" :label-width="formLabelWidth">
							<el-date-picker v-model="ruleForm.leaveDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期"> </el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="出生日期" prop="birthday" :label-width="formLabelWidth">
							<el-date-picker v-model="ruleForm.birthday" type="date" value-format="YYYY-MM-DD" placeholder="选择日期"> </el-date-picker>
						</el-form-item>
					</el-col>
					
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="备注说明" :label-width="formLabelWidth">
							<el-input v-model="ruleForm.remark" type="textarea" placeholder="请输入内容" clearable />
						</el-form-item>
					</el-col>

					<el-divider content-position="left">上传信息</el-divider>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label-width="50">
							<div style="color: #ccc">注意：员工照片只能上传一张；身份证可以上传两张，正面和反面；点击提交按钮才表示上传成功；</div>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="员工照片" :label-width="formLabelWidth">
							<div class="upload-d">
								<el-upload
									ref="uploadFileOne"
									action="#"
									accept=".jpg,.png,.jpeg"
									:multiple="false"
									:show-file-list="false"
									:auto-upload="false"
									class="upload-style"
									:on-change="empImageChange"
									style="width: 100%"
								>
									<el-input v-if="!isViewOne" readOnly slot="" placeholder="请点击输入框上传员工照片" />
									<el-input v-if="isViewOne && !showImg" v-model="empImageVal" readOnly slot="" />
								</el-upload>

								<template v-if="isViewOne">
									<div v-if="showImg" style="color: #67c23a" @click="lookImgClick(ruleForm.empImage_Path)" class="path_look">
										<span class="img-span" style="cursor: pointer">点击预览上传照片</span>
									</div>
									<div class="icon-d upload-b">
										<el-tooltip effect="dark" content="移 除" placement="top">
											<el-icon @click="cancelDepClickOne" style="background: unset !important; cursor: pointer">
												<Delete />
											</el-icon>
										</el-tooltip>
									</div>
								</template>
							</div>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="上传身份证" :label-width="formLabelWidth">
							<div class="upload-d">
								<template v-if="!isDisable">
									<el-upload
										ref="uploadFileTwo"
										accept=".jpg,.png,.jpeg"
										action="#"
										multiple
										:show-file-list="false"
										:auto-upload="false"
										class="upload-style"
										:on-change="cardChange"
										:limit="limitList"
										:on-exceed="handleExceed"
										:on-remove="onRemove"
										style="width: 100%"
									>
										<el-button class="select-btn-s" v-if="showBtn" style="margin: 10px" type="primary">继续上传</el-button>
										<el-select
											v-if="isViewTwo"
											v-model="fileVal"
											multiple
											collapse-tags
											collapse-tags-tooltip
											placeholder="上传身份证"
											@change="fileChange"
											@focus="fileFocus"
											popper-class="set-select"
											:popper-append-to-body="false"
										>
											<el-option v-for="item in fileOptions" :key="item.uid" :label="item.name" :value="item.uid" />
										</el-select>
										<el-input v-else readOnly slot="" placeholder="上传身份证" />
									</el-upload>
								</template>
								<template v-else>
									<div style="color: #c0c4cc" class="path_look_sfz">
										<span>证件已上传</span>
									</div>
								</template>
							</div>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<template v-if="titleCon === '编辑'">
				<el-divider content-position="left"> 身份证信息 </el-divider>
				<el-table class="table-s" :data="fileListArr" style="width: 100%" border>
					<el-table-column min-width="160" prop="name" :show-overflow-tooltip="true" label="证件名称" align="center" />
					<el-table-column min-width="270" prop="path" :show-overflow-tooltip="true" label="证件路径" align="center" />
					<el-table-column min-width="120" prop="suffix" :show-overflow-tooltip="true" label="文件后缀" align="center" />
					<el-table-column min-width="120" prop="suffix" :show-overflow-tooltip="true" label="缩略图" align="center">
						<template #default="scope">
							<img style="width: 20px; height: 20px" :src="pathData + scope.row.path" />
						</template>
					</el-table-column>
					<el-table-column min-width="160" prop="createdTime" :show-overflow-tooltip="true" label="上传时间" align="center" />
					<el-table-column min-width="120" prop="createdUserName" :show-overflow-tooltip="true" label="上传人" align="center" />
					<el-table-column min-width="120" :show-overflow-tooltip="true" label="操作" align="center" fixed="right">
						<template #default="scope">
							<el-link target="_blank" :href="pathData + scope.row.path">预览</el-link>
							<el-button @click="deleteHandle(scope.row.id)" class="icon-e" icon="ele-Delete" size="small" text type="danger"> 删除 </el-button>
						</template>
					</el-table-column>
				</el-table>
			</template>

			<template #footer>
				<el-button @click="cancelUseClick">取消</el-button>
				<el-button :loading="repeatDis" :disabled="repeatDis" @click="submitForm(ruleFormRef)" type="primary">提交</el-button>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts">
import { defineComponent, ref, Ref, reactive, computed, toRefs, toRaw, watch, onMounted } from 'vue';
import { FormInstance, FormRules, ElMessage, ElMessageBox } from 'element-plus';
import { sysEmpAddEmp, sysOrgTree, sysEmpUpdateEmp, sysFileInfoDelete } from '/@/api/centerControl/oms';
import useCurrentInstance from '/@/utils/hook/useCurrentInstance';
import { AnyTxtRecord } from 'dns';
import { sysPosList } from '/@/api/centerControl/pubilc';

/*** 定义接口基础数据类型 */
interface formType {
	repeatDis: Boolean;
	ruleForm: ruleFormType;
}
/*** form 表单数据类型 */
type ruleFormType = {
	id?: Number;
	cardId_File: String; // 身份证附件
	empImage_Path?: String;

	empImage_File: String; // 员工照片
	jobNum: String; // 工号

	politicalIdentity: String;
	maritalStatus: String;

	orgId: Number; // 机构Id
	orgName: String; // 机构名称

	empName: String; // 员工姓名
	birthday: String; // 生日
	type: Number; // 1部门/2班组
	gender: String; // 性别 1男/2女
	cardId: String; // 身份证号
	cardImage: Number; // 身份证照片
	empImage: Number; // 员工照片
	email: String; // 邮箱地址
	familyAddress: String; // 家庭住址
	phone: String; // 手机号
	emergencyPhone: String; // 紧急联系人方式
	// physicalCounts: Number, // 体检提交数量
	inductionDate: String; // 入职日期
	leaveDate: String; // 离职日期
	isEnable: Boolean; // 是否启用
	remark: String; // 备注

	posId:any
};
export default defineComponent({
	name: 'add-edit-dep-manage',
	components: {},
	props: {
		isUseDialog: {
			type: Boolean,
			default: false,
		},
		repairInfo: {
			type: String,
			default: '',
		},
	},
	setup(props, ctx) {
		// const { proxy } = useCurrentInstance();
		// const $t = proxy.$t;
		const maritalStatusOptions = [
			{ label: '未婚', value: '未婚' },
			{ label: '已婚', value: '已婚' },
		];

		const politicalIdentityOptions = [
			{ label: '群众', value: '群众' },
			{ label: '团员', value: '团员' },
			{ label: '党员', value: '党员' },
		];

		const posIdList: any = ref([]);
		const titleCon = ref();
		const ruleFormRef = ref();
		const treeData = ref([]);
		const empImageVal = ref('');
		const cardVal = ref('');
		const uploadFileOne: Ref = ref(null);
		const uploadFileTwo: Ref = ref(null);
		const treeRef: Ref = ref(null);
		const pathData = ref(import.meta.env.VITE_API_URL + '/'); // 获取地址
		const fileListArr = ref([]);
		const isDisable = ref(false);

		const fileVal: any = ref([]); // 上传身份证下拉框model值
		const fileOptions: any = ref([]);
		const showImg = ref(false);
		const showBtn = ref(false);
		const isViewOne = ref(false);
		const isViewTwo = ref(false);
		const limitList = ref(2);

		const arrContrastFun = (arr1?: any, arr2?: any) => {
			let newArr = [];
			if (arr1.length !== 0 && arr2.length !== 0) {
				for (let i = 0; i < arr1.length; i++) {
					for (let e = 0; e < arr2.length; e++) {
						if (arr1[i] === arr2[e].uid) {
							newArr.push(arr2[e]);
						}
					}
				}
			}
			return newArr;
		};

		/*** onRemove 移除文件钩子函数 */
		const onRemove = (file: any, fileList: any) => {
			let getFile = JSON.parse(JSON.stringify(fileList));
			if (getFile.length === 0) {
				showBtn.value = false;
			}
		};

		/*** fileFocus select获取焦点的时候触发 */
		const fileFocus = () => {
			fileOptions.value = arrContrastFun(toRaw(fileVal.value), toRaw(fileOptions.value));
		};

		/*** handleExceed 当文件上传超出指定个数的时候提示事件 */
		const handleExceed = () => {
			ElMessage({
				message: '最多上传' + limitList.value + '张',
				type: 'warning',
				duration: 2000,
			});
		};

		/*** fileChange select改变事件 */
		const fileChange: any = (val: any) => {
			uploadFileTwo.value.handleRemove((e: any) => {});
			if (val.length === 0) {
				isViewTwo.value = false;
				uploadFileTwo.value.clearFiles();
				fileVal.value = [];
				fileOptions.value = [];
			}
			if (props.repairInfo === '') {
				if (val.length < 2 && val.length !== 0) {
					showBtn.value = true;
				} else {
					showBtn.value = false;
				}
			} else {
				if (limitList.value === 1) {
					showBtn.value = false;
				}
				if (limitList.value === 2) {
					console.log('4');
					if (val.length < 2 && val.length !== 0) {
						console.log('5');
						showBtn.value = true;
					} else {
						console.log('6');
						showBtn.value = false;
					}
				}
			}
			fileOptions.value = arrContrastFun(val, toRaw(fileOptions.value));
		};

		/*** cardChange 上传身份证改变事件 */
		const cardChange = (item: any) => {
			isViewTwo.value = true;
			console.log(item, 'item');

			if (toRaw(fileOptions.value).length !== 0) {
				toRaw(fileOptions.value).map((i: any) => {
					if (i.name !== item.name) {
						fileOptions.value.push(item);
						fileVal.value.push(item.uid);
						console.log(fileOptions.value, '2');
						let arr = [];
						fileOptions.value.forEach((element) => {
							arr.push(element.raw);
						});
						state.ruleForm.cardId_File = arr;
					} else {
						uploadFileTwo.value.handleRemove((e: any) => {});
						ElMessage({
							message: '上传失败，该文件已上传',
							type: 'warning',
							duration: 2000,
						});
					}
				});
			} else {
				fileOptions.value.push(item);
				fileVal.value.push(item.uid);
				let arr = [];
				arr.push(item.raw);
				state.ruleForm.cardId_File = arr;
				console.log(state.ruleForm.cardId_File, arr);
			}

			if (props.repairInfo === '') {
				if (toRaw(fileOptions.value).length !== 0 && toRaw(fileOptions.value).length < 2) {
					showBtn.value = true;
				} else {
					showBtn.value = false;
				}
			} else {
				if (limitList.value === 1) {
					showBtn.value = false;
				}
				if (limitList.value === 2) {
					if (toRaw(fileOptions.value).length !== 0 && toRaw(fileOptions.value).length < 2) {
						showBtn.value = true;
					} else {
						showBtn.value = false;
					}
				}
			}
		};

		/*** orgChange 部门组织改变事件 */
		const orgChange = (val: any) => {
			let getVal = toRaw(treeRef.value.getCurrentNode());
			state.ruleForm.orgName = getVal.title;
			state.ruleForm.orgId = val;
		};

		/*** phoneBlur 手机号码失去焦点事件 */
		const phoneBlur = (rule: any, value: any, callback: any) => {
			let val = state.ruleForm.phone.replace(/\s*/g, '');
			if (val === '') {
				callback(new Error('请输入手机号'));
			} else {
				if (val.length !== 11) {
					callback(new Error('请输入11位有效手机号'));
					state.ruleForm.phone = '';
				} else {
					if (isNaN(parseFloat(val))) {
						callback(new Error('请输入手机号'));
						state.ruleForm.phone = '';
					} else {
						if (parseFloat(val).toString().length !== 11) {
							callback(new Error('请输入11位有效手机号'));
							state.ruleForm.phone = '';
						} else {
							callback();
						}
					}
				}

				if (state.ruleForm.emergencyPhone !== '' && state.ruleForm.phone === state.ruleForm.emergencyPhone) {
					callback(new Error('联系方式不能与紧急联系人号码相同'));
					state.ruleForm.phone = '';
				} else {
					callback();
				}
			}
		};

		/*** emergencyBlur 紧急联系人号码失去焦点事件 */
		const emergencyBlur = (rule: any, value: any, callback: any) => {
			let val = state.ruleForm.emergencyPhone.replace(/\s*/g, '');
			if (val === '') {
				callback(new Error('请输入紧急联系人方式'));
			} else {
				if (val.length !== 11) {
					callback(new Error('请输入11位有效手机号'));
					state.ruleForm.emergencyPhone = '';
				} else {
					if (isNaN(parseFloat(val))) {
						callback(new Error('请输入手机号'));
						state.ruleForm.emergencyPhone = '';
					} else {
						if (parseFloat(val).toString().length !== 11) {
							callback(new Error('请输入11位有效手机号'));
							state.ruleForm.emergencyPhone = '';
						}
					}
				}

				if (state.ruleForm.phone !== '' && state.ruleForm.emergencyPhone === state.ruleForm.phone) {
					callback(new Error('紧急联系人号码不能与联系方式相同'));
					state.ruleForm.emergencyPhone = '';
				} else {
					callback();
				}
			}
		};

		/*** lookImgClick 员工图片预览 */
		const lookImgClick = (val: any) => {
			// window.location.href = 'www.baidu.com' // 覆盖当前页
			window.open(toRaw(pathData.value) + val, '_blank'); // 打开新页面
		};

		/*** empImageChange 上传员工照片改变事件 */
		const empImageChange = (item: any, fileList: any) => {
			if (fileList.length > 1) {
				fileList.splice(0, 1); // 当上传文件大于1的时候替换，移除之前的文件（0是要删除数组的下标，1是要删除的数量）
			}
			state.ruleForm.empImage_File = [item.raw];
			isViewOne.value = true;
			empImageVal.value = item.name;
			console.log(state.ruleForm, 'state.ruleForm');
		};

		/*** state 引用接口定义基础数据初始值 */
		const state = reactive<formType>({
			repeatDis: false,
			ruleForm: {} as ruleFormType,
		});

		/*** emailBlur 邮箱验证 */
		const emailBlur = (rule: any, value: any, callback: any) => {
			let mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
			if (value === '') {
				callback(new Error('请输入邮箱'));
			} else {
				if (value) {
					let str = value.replace(/\s*/g, '');
					if (mailReg.test(str)) {
						state.ruleForm.email = str;
						callback();
					} else {
						state.ruleForm.email = '';
						callback(new Error('格式有误，请重新输入'));
					}
				} else {
					callback(new Error('请输入邮箱'));
				}
			}
		};

		/*** 基础验证 rules */
		const rules = reactive<FormRules>({
			/*** 放置验证 */
			cardId_File: [{ required: true, message: '请上传身份证附件', trigger: 'change' }],
			empImage_File: [{ required: true, message: '请上传员工照片', trigger: 'change' }],
			jobNum: [{ required: true, message: '请输入工号', trigger: 'blur' }],
			posIds: [{ required: true, message: '请选择岗位', trigger: 'blur' }],

			politicalIdentity: [{ required: true, message: '请输入政治身份', trigger: 'blur' }],
			maritalStatus: [{ required: true, message: '请输入婚姻状况', trigger: 'blur' }],

			orgName: [{ required: true, message: '请选择部门', trigger: 'change' }],
			empName: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
			birthday: [{ required: true, message: '请选择生日', trigger: 'change' }],
			cardId: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
			email: [{ validator: emailBlur, required: true, trigger: 'blur' }],
			familyAddress: [{ required: true, message: '请输入家庭住址', trigger: 'blur' }],
			phone: [
				// { required: true, message: '请输入手机号', trigger: 'blur' },
				{ validator: phoneBlur, required: true, trigger: 'blur' },
			],
			emergencyPhone: [
				// { required: true, message: '请输入紧急联系人方式', trigger: 'blur' },
				{ validator: emergencyBlur, required: true, trigger: 'blur' },
			],
			// physicalCounts: [
			//     { required: true, message: '请输入体检提交数量', trigger: 'blur' },
			// ],
			inductionDate: [{ required: true, message: '请选择入职日期', trigger: 'change' }],
		});

		/*** handleClose 关闭按钮点击事件 */
		const handleClose = () => {
			cancelUseClick();
		};

		/*** cancelUseClick 取消事件 */
		const cancelUseClick = () => {
			clearFileFun();
			ctx.emit('cancelUseClick');
		};

		/*** submitForm 提交事件 */
		const submitForm = (formEl: FormInstance | undefined) => {
			if (!formEl) return;
			formEl.validate(async (valid) => {
				if (valid) {
					let getData = toRaw(state.ruleForm);
					let param: any = {};
					getData.gender === '1' ? (param.gender = 1) : (param.gender = 2);
					let fileArr: any = [];
					if (toRaw(fileOptions.value).length !== 0) {
						toRaw(fileOptions.value).map((i: any) => {
							fileArr.push(i.raw);
						});
					}
					console.log(fileArr, state.ruleForm.cardId_File);
					param.cardId_File = fileArr;
					// if(fileArr.length === 2){
					//     param.cardId_File = fileArr[0];
					//     param.CardId_File1 = fileArr[1];
					// }else if(fileArr.length !== 0){
					//     param.cardId_File = fileArr[0];
					// }

					const { gender, ...getArr } = getData;
					let valObj = { ...getArr, ...param };
					for (let i in valObj) {
						if (valObj[i] == null) {
							valObj[i] = '';
						}
					}
					if (props.repairInfo === '') {
						state.repeatDis = true;
						let res: any = await sysEmpAddEmp(valObj);
						if (res.success) {
							ctx.emit('updateData');
							ctx.emit('controlUseClick');
							clearFileFun();
							state.repeatDis = false;
						}
					} else {
						state.repeatDis = true;
						let res: any = await sysEmpUpdateEmp(valObj);
						if (res.success) {
							ctx.emit('updateData');
							ctx.emit('controlUseClick');
							clearFileFun();
							state.repeatDis = false;
						}
					}
				} else {
					console.log('error submit!');
					return false;
				}
			});
		};
		/*** clean 清空数据 */
		const clean = () => {
			ruleFormRef.value.resetFields();
		};
		/*** clearFileFun 清空文件函数 */
		const clearFileFun = () => {
			// 清空文件上传数据
			if (!isDisable.value) {
				uploadFileTwo.value.clearFiles();
			}
			uploadFileOne.value.clearFiles();
			empImageVal.value = '';
			fileOptions.value = [];
			fileVal.value = [];
		};

		/*** 监听isUseDialog的变化 */
		watch(
			() => props.isUseDialog,
			(newVal) => {
				getOrgTree();
				if (newVal) {
					// 状态数据重置
					state.repeatDis = false;
					showImg.value = false;
					showBtn.value = false;
					isViewOne.value = false;
					isViewTwo.value = false;
					isDisable.value = false;
					fileListArr.value = [];
					limitList.value = 2;
					// 状态数据重置
					if (props.repairInfo !== '') {
						titleCon.value = '编辑';
						let getData = JSON.parse(props.repairInfo);
						console.log(getData);

						if (JSON.parse(props.repairInfo).empImage_Path) {
							isViewOne.value = true;
							showImg.value = true;
						}
						if (JSON.parse(props.repairInfo).cardId_Path) {
							if (JSON.parse(props.repairInfo).cardId_Path.length === 2) {
								isDisable.value = true;
							} else if (JSON.parse(props.repairInfo).cardId_Path.length === 1) {
								limitList.value = 1;
								showBtn.value = false;
							}
							let filePath = JSON.parse(props.repairInfo).cardId_Path;
							let fileArr: any = [];
							filePath.map((i: any) => {
								let fileData: any = {};
								fileData.id = i.id;
								fileData.createdTime = i.createdTime;
								fileData.createdUserName = i.createdUserName;
								fileData.name = i.path.split('.')[0].split('/')[i.path.split('.')[0].split('/').length - 1];
								fileData.path = i.path;
								fileData.suffix = i.path.split('.')[i.path.split('.').length - 1];
								fileArr.push(fileData);
							});
							fileListArr.value = fileArr;
						}
						let setPara: any = {};
						getData.birthday === '1900-01-01 00:00:00' || !getData.birthday ? (setPara.birthday = '') : (setPara.birthday = getData.birthday); // 生日
						getData.inductionDate === '1900-01-01 00:00:00' || !getData.inductionDate ? (setPara.inductionDate = '') : (setPara.inductionDate = getData.inductionDate); // 入职日期
						getData.leaveDate === '1900-01-01 00:00:00' || !getData.leaveDate ? (setPara.leaveDate = '') : (setPara.leaveDate = getData.leaveDate); // 离职日期
						const { birthday, inductionDate, leaveDate, ...setData } = getData;
						state.ruleForm = { ...setPara, ...setData };
						state.ruleForm.posIds = getData.positions.map((i: any) => {
							return i.posId
						});
					} else {
						titleCon.value = '新增';
						state.ruleForm = {
							cardId_File: '', // 身份证附件

							empImage_File: '', // 员工照片
							jobNum: '', // 工号

							orgId: 0, // 机构Id
							orgName: '', // 机构名称

							empName: '', // 员工姓名
							type: 1, // 1部门/2班组
							gender: '1', // 性别
							cardId: '', // 身份证号
							cardImage: 0, // 身份证照片
							empImage: 0, // 员工照片
							email: '', // 邮箱地址
							familyAddress: '', // 家庭住址
							phone: '', // 手机号
							emergencyPhone: '', // 紧急联系人电话
							// physicalCounts: 0, // 体检提交数量
							birthday: '', // 生日
							inductionDate: '', // 入职日期
							leaveDate: '', // 离职日期
							isEnable: true, // 是否启用
							remark: '', // 备注
						};
					}
					console.log(state.ruleForm);
				}
			}
		);

		/*** isUseDialog 响应弹窗的关闭  */
		const isUseDialog = computed(() => {
			return props.isUseDialog;
		});

		/*** 部门人员改变事件 */
		const teamSelect = (val: any) => {
			console.log(val, 'val');
		};

		/*** craftSelect 所属工种改变事件 */
		const craftSelect = (val: any) => {
			console.log(val, 'val');
		};

		/*** cancelDepClickOne 人员图像上传移除文件 */
		const cancelDepClickOne = () => {
			ElMessage({
				message: '删除成功',
				type: 'success',
				duration: 1000,
				onClose: () => {
					uploadFileOne.value.clearFiles();
					empImageVal.value = '';
					isViewOne.value = false;
					showImg.value = false;
					state.ruleForm.empImage_File = '';
				},
			});
		};

		const getOrgTree = async () => {
			let param: any = {};
			param.type = 1;
			param.IsAddProvider = true;
			let res: any = await sysOrgTree(param);
			if (res.success) {
				treeData.value = res.data;
			}
		};

		/*** deleteHandle 删除数据事件 */
		const deleteHandle = async (val: String | Number) => {
			ElMessageBox.confirm('请确定是否删除此条数据', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(async () => {
					let param = { id: val };
					try {
						let res: any = await sysFileInfoDelete(param);
						if (res.success) {
							let getArr = toRaw(fileListArr.value).filter((i: any) => {
								return i.id !== val;
							});
							if (uploadFileTwo.value) {
								isViewTwo.value = false;
								showBtn.value = false;
								uploadFileTwo.value.clearFiles();
								fileVal.value = [];
								fileOptions.value = [];
							}
							if (getArr.length < 2) {
								isDisable.value = false;
							}
							if (getArr.length === 1) {
								limitList.value = 1;
								showBtn.value = false;
							}
							if (getArr.length === 0) {
								limitList.value = 2;
							}
							fileListArr.value = getArr;
							ctx.emit('updateData');
						}
					} catch (err) {
						return;
					}
				})
				.catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
				});
		};

		/*** birthChange 生日改变事件 */
		// const birthChange = (val:any) => {
		//     console.log(val,'val')
		//     if(!val && val !== ''){
		//         birthday
		//     }
		// }

		onMounted(async () => {
			const res = await sysPosList({});
			console.log(res, 'res');
			posIdList.value = res.data.map((item: any) => {
				return {
					label: item.name,
					value: item.id,
				};
			});
		});

		const posChange = (val) => {
			console.log(val,"val");
			state.ruleForm.posIds = val;
			console.log(state.ruleForm.posIds);
			
		}

		return {
			posChange,
			handleClose,
			submitForm,
			cancelUseClick,
			clean,
			ruleFormRef,
			titleCon,
			...toRefs(state),
			isUseDialog,
			rules,
			cancelDepClickOne,
			isViewOne,
			isViewTwo,
			formLabelWidth: '120px',
			teamSelect,
			treeData,
			craftSelect,
			empImageChange,
			empImageVal,
			cardVal,
			treeProps: { label: 'title', children: 'children' },
			uploadFileOne,
			uploadFileTwo,
			orgChange,
			treeRef,
			fileVal,
			fileOptions,
			showBtn,
			onRemove,
			fileFocus,
			handleExceed,
			fileChange,
			cardChange,
			pathData,
			showImg,
			lookImgClick,
			fileListArr,
			deleteHandle,
			isDisable,
			limitList,
			maritalStatusOptions,
			politicalIdentityOptions,
			posIdList,
			// birthChange,
		};
	},
});
</script>
<style scoped lang="scss">
#add-edit-dep-manage {
	:deep(.el-select) {
		width: 100%;
	}
	:deep(.el-input) {
		width: 100%;
	}
	:deep(.el-upload) {
		width: 100%;
	}
	.img-span {
		color: #0052d9;
	}
	.table-s {
		:deep(.el-icon) {
			margin-right: 0px !important;
			margin-left: 12px !important;
		}
	}
	.path_look_sfz {
		display: block;
		width: 100%;
		border: 1px solid #e4e7ed;
		border-radius: 4px;
		span {
			display: block;
			margin-left: 15px;
			color: #606266;
		}
	}
	.upload-d {
		position: relative;
		width: 100%;
		:deep(.el-upload) {
			width: 100%;
		}
		.path_look {
			display: block;
			width: 100%;
			border: 1px solid #e4e7ed;
			border-radius: 4px;
			position: absolute;
			left: 0;
			top: 0;
			span {
				display: block;
				margin-left: 15px;
				color: #606266;
			}
		}
		.upload-in {
			position: absolute;
			left: 0;
			top: 0;
		}
		.select-btn-s {
			position: absolute;
			top: 2px;
			right: 1px;
			z-index: 3;
			margin: 0 !important;
			border: none !important;
			background: rgba(255, 255, 255, 1) !important;
			color: #0052d9 !important;
			height: 28px;
		}
		.select-btn-s:active {
			color: #0052d9 !important;
		}
		.select-btn-s:hover {
			color: #0052d9 !important;
		}
		.upload-b {
			display: flex;
			align-items: center;
			position: absolute;
			top: 10px;
			right: 10px;
			line-height: initial;
			background: unset !important;
			:deep(a) {
				background: unset !important;
				margin-right: 10px;
			}
			:deep(span) {
				background: unset !important;
			}
		}
	}
}
</style>
